/**
 * 
 */
package com.watchthelan.service.login;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.watchthelan.domain.Administrator;
import com.watchthelan.service.administrator.AdministratorManager;

/**
 * @author robert
 *
 */
public class LoginValidator implements Validator {

	@Override
	public boolean supports(Class arg0) {
		return Administrator.class.equals(arg0);
	}

	@Override
	public void validate(Object object, Errors errors) {
		Administrator administrator = (Administrator) object;
		if ("".equals(administrator.getUsername())) {
			errors.rejectValue("username", "error.administrator.name", null, "Value required.");
		}
		
		//verify username and password
		ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "../applicationContext.xml"});
		AdministratorManager administratorManager = (AdministratorManager) ctx.getBean("administratorManager");
		Administrator adm = administratorManager.getAdministratorByUsername(administrator.getUsername());
		if (adm == null ) {
			errors.rejectValue("username", "error.login");
		} else {
			if (!adm.getPassword().equals(administrator.getPassword())) {
				errors.rejectValue("username", "error.login");
			}
			if (!adm.getEnabled()) {
				errors.rejectValue("username", "error.login.enabled");
			}
		}
	}
}
